package com.hp.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * CGLib动态代理
 */
public class CGlibProxy implements MethodInterceptor {

    //被代理者对象
    private Object target;

    /**
     * 返回代理对象
     * @param target
     * @return
     */
    public Object newProxyInstance(Object target){
        this.target = target;
        //创建CGLib的增强器对象
        Enhancer enhancer = new Enhancer();
        //给增强器设置父类
        enhancer.setSuperclass(target.getClass());
        //设置方法拦截器的实现对象
        enhancer.setCallback(this);
        //返回代理对象
        return enhancer.create();
    }

    /**
     * 拦截方法
     * @param o
     * @param method
     * @param objects
     * @param methodProxy
     * @return
     * @throws Throwable
     */
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("CGLib给你打广告！");
        Object obj = method.invoke(target,objects);
        System.out.println("CGLib给你售后服务！！");
        return obj;
    }
}
